package com.threeti.mecool.mobile.controller;

import static com.threeti.mecool.mobile.CommandConst.CMD_USER_CHANGEPASS;
import static com.threeti.mecool.mobile.CommandConst.CMD_USER_COMMUNICATIONS;
import static com.threeti.mecool.mobile.MessageConst.MSG_COMMON_001;
import static com.threeti.mecool.mobile.MessageConst.MSG_USER_001;
import static com.threeti.mecool.mobile.MessageConst.MSG_USER_002;
import static com.threeti.mecool.mobile.MessageConst.MSG_USER_003;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.threeti.mecool.core.domain.model.Communication;
import com.threeti.mecool.core.infrastructure.persistence.CommunicationRepository;
import com.threeti.mecool.core.infrastructure.persistence.UserRepository;
import com.threeti.mecool.mobile.interfaces.PageInfo;
import com.threeti.mecool.mobile.interfaces.ResponseDto;
import com.threeti.mecool.mobile.interfaces.assembler.UserAssembler;

@Controller
@RequestMapping(value = "/user")
public class UserMobiController {
  @Autowired
  UserRepository userRepo;
  
  @Autowired
  private CommunicationRepository commRepo;

  @RequestMapping(value = "/changepassword")
  @ResponseBody
  public ResponseDto changePassword(@RequestParam(required = true) String loginName, @RequestParam(required = true) String oldPassword,@RequestParam(required = true) String newPassword) {
    
    if (StringUtils.isBlank(newPassword)) {
      return ResponseDto.withBizFailureMsg(CMD_USER_CHANGEPASS, MSG_USER_001);
    }
    
    int cnt = userRepo.changePasswordByLoginNameAndOldPassword(loginName, oldPassword, newPassword);
    if (cnt == 0) {
      return ResponseDto.withBizFailureMsg(CMD_USER_CHANGEPASS, MSG_USER_002);
    }

    return ResponseDto.withBizSuccessMsg(CMD_USER_CHANGEPASS, MSG_COMMON_001);
  }

  @RequestMapping(value = "/commuications")
  @ResponseBody
  public ResponseDto communications(@RequestParam(required = true) String userId,@RequestParam(required = true) int page, @RequestParam(required = true) int size) {
    Page<Communication> comms = commRepo.findAll(new PageRequest(page, size));
    if (!comms.hasContent()) {
      return ResponseDto.withBizFailureMsg(CMD_USER_COMMUNICATIONS, MSG_USER_003);
    }
    return 
        ResponseDto.with(CMD_USER_COMMUNICATIONS, "1")
        .withBizSuccessPageBody("commuications", UserAssembler.toDtoList(comms.getContent()), PageInfo.page(comms.getTotalElements(), comms.hasNextPage()));
  }
}
